<script setup lang="jsx">
import { ref, onMounted, reactive, computed } from 'vue';
import { useEcharts } from '@/hooks/common/echarts';
import * as XLSX from 'xlsx';
import { message } from 'ant-design-vue';

// 制造业堆叠面积图 - 显示不同产品线的产量趋势
const { domRef: stackedAreaChartRef } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['手机壳', '数据线', '充电器', '保护膜', '无线充'],
    top: 0,
    right: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '产量(件)',
      axisLabel: {
        margin: 25
      },
    }
  ],
  series: [
    {
      name: '手机壳',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [12000, 13200, 10100, 13400, 9000, 23000, 21000, 15000, 18000, 16000, 19000, 21000]
    },
    {
      name: '数据线',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [22000, 18200, 19100, 23400, 29000, 33000, 31000, 25000, 28000, 26000, 29000, 31000]
    },
    {
      name: '充电器',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [15000, 23200, 20100, 15400, 19000, 33000, 41000, 35000, 38000, 36000, 39000, 41000]
    },
    {
      name: '保护膜',
      type: 'line',
      stack: 'Total',
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [32000, 33200, 30100, 33400, 39000, 33000, 32000, 35000, 38000, 36000, 39000, 42000]
    },
    {
      name: '无线充',
      type: 'line',
      stack: 'Total',
      label: {
        show: true,
        position: 'top'
      },
      areaStyle: {},
      emphasis: {
        focus: 'series'
      },
      data: [8200, 9320, 9010, 9340, 12900, 13300, 13200, 15000, 18000, 16000, 19000, 21000]
    }
  ]
}), false);

// 制造业条形图 - 显示各生产线效率
const { domRef: barChartRef } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
      }
    },
  legend: {
    data: ['计划产量', '实际产量', '良品数'],
    top: 0,
    right: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: ['A号线', 'B号线', 'C号线', 'D号线', 'E号线', 'F号线', 'G号线']
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '数量(件)'
    }
  ],
  series: [
    {
      name: '计划产量',
      type: 'bar',
      barGap: 0,
      label: {
        show: true,
       position: 'top',
        distance: 10
      },
      emphasis: {
        focus: 'series'
      },
      data: [10000, 12000, 11000, 9000, 13000, 11500, 10500]
    },
    {
      name: '实际产量',
      type: 'bar',
      label: {
        show: true,
        position: 'insideTop',
        distance: 10
      },
      emphasis: {
        focus: 'series'
      },
      data: [9800, 11500, 10800, 8900, 12500, 11200, 10300]
    },
    {
      name: '良品数',
      type: 'bar',
      label: {
        show: true,
        position: 'insideBottom',
        distance: 10
      },
      emphasis: {
        focus: 'series'
      },
      data: [9600, 11200, 10500, 8700, 12200, 10900, 10100]
    }
  ]
}), false);

// 表格列定义 - 显示生产计划执行情况
const tableColumns = [
  {
    key: 'id',
    dataIndex: 'id',
    title: '序号',
    width: 8
  },
  {
    key: 'productLine',
    dataIndex: 'productLine',
    title: '生产线',
    width: 10
  },
  {
    key: 'productName',
    dataIndex: 'productName',
    title: '产品名称',
    width: 12
  },
  {
    key: 'plannedQuantity',
    dataIndex: 'plannedQuantity',
    title: '计划产量',
    width: 10
  },
  {
    key: 'actualQuantity',
    dataIndex: 'actualQuantity',
    title: '实际产量',
    width: 10
  },
  {
    key: 'defectQuantity',
    dataIndex: 'defectQuantity',
    title: '不良品数',
    width: 10
  },
  {
    key: 'yieldRate',
    dataIndex: 'yieldRate',
    title: '良品率(%)',
    width: 10
  },
  {
    key: 'executionRate',
    dataIndex: 'executionRate',
    title: '执行率(%)',
    width: 10
  },
  {
    key: 'manager',
    dataIndex: 'manager',
    title: '负责人',
    width: 10
  },
  {
    key: 'status',
    dataIndex: 'status',
    title: '状态',
    width: 10
  }
];

// 存储所有数据（包括原始数据和导入的数据）
const allTableData = ref([]);

// 生成写死的表格数据 - 制造业生产计划执行情况
const generateTableData = (page, pageSize) => {
  const productLines = ['A号线', 'B号线', 'C号线', 'D号线', 'E号线', 'F号线', 'G号线'];
  const productNames = ['手机壳', '数据线', '充电器', '保护膜', '无线充'];
  const managers = ['张经理', '李主管', '王主任', '赵班长', '钱组长', '孙技术员', '周工程师'];
  const statuses = ['已完成', '进行中', '待审核', '已暂停'];

  const data = [];
  const totalItems = 1000; // 总共1000条数据

  // 根据页码和页面大小生成对应的数据
  const startIndex = (page - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, totalItems);

  for (let i = startIndex; i < endIndex; i++) {
    const productLine = productLines[Math.floor(Math.random() * productLines.length)];
    const productName = productNames[Math.floor(Math.random() * productNames.length)];
    const manager = managers[Math.floor(Math.random() * managers.length)];
    const status = statuses[Math.floor(Math.random() * statuses.length)];

    // 随机生成产量数据
    const plannedQuantity = Math.floor(Math.random() * 5000) + 5000; // 5000-10000
    const actualQuantity = Math.floor(plannedQuantity * (0.95 + Math.random() * 0.1)); // 95%-105% of planned
    const defectQuantity = Math.floor((plannedQuantity - actualQuantity) * (0.1 + Math.random() * 0.3)); // 10%-40% of difference
    const yieldRate = ((actualQuantity - defectQuantity) / plannedQuantity * 100).toFixed(2);
    const executionRate = (actualQuantity / plannedQuantity * 100).toFixed(2);

    data.push({
      key: i,
      id: i+1,
      productLine,
      productName,
      plannedQuantity: plannedQuantity.toLocaleString(),
      actualQuantity: actualQuantity.toLocaleString(),
      defectQuantity: defectQuantity.toLocaleString(),
      yieldRate: yieldRate,
      executionRate: executionRate,
      manager,
      status
    });
  }
  return data;
};

// 获取行类名
const getRowClass = (index) => {
  return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};

// 排序状态
const sortState = reactive({
  field: '',
  order: ''
});

// 处理排序
const handleSort = (field) => {
  // 如果点击的是当前排序字段，则切换排序方式
  if (sortState.field === field) {
    if (sortState.order === 'asc') {
      sortState.order = 'desc';
    } else if (sortState.order === 'desc') {
      sortState.order = '';
      sortState.field = '';
    } else {
      sortState.order = 'asc';
    }
  } else {
    // 点击新字段，默认升序
    sortState.field = field;
    sortState.order = 'asc';
  }
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 50,
  total: 1000,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
});

// 表格数据
const tableData = ref([]);

// 更新当前页数据
const updateCurrentPageData = () => {
  const startIndex = (pagination.current - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  tableData.value = allTableData.value.slice(startIndex, endIndex);
};

// 初始化数据
onMounted(() => {
  // 生成初始的1000条数据
  allTableData.value = [];
  for (let i = 0; i < 20; i++) { // 20页 * 50条 = 1000条
    const pageData = generateTableData(i + 1, 50);
    allTableData.value.push(...pageData);
  }
  updateCurrentPageData();
});

// 处理分页变化
const handlePageChange = (current, pageSize) => {
  pagination.current = current;
  pagination.pageSize = pageSize;
  updateCurrentPageData();

  // 重置排序状态
  sortState.field = '';
  sortState.order = '';
};

// 计算排序后的数据
const sortedTableData = computed(() => {
  if (!sortState.field || !sortState.order) {
    return tableData.value;
  }

  // 创建数据副本以避免修改原始数据
  const sortedData = [...tableData.value];

  return sortedData.sort((a, b) => {
    let aValue = a[sortState.field];
    let bValue = b[sortState.field];

    // 去除千位分隔符
    if (typeof aValue === 'string') {
      aValue = aValue.replace(/,/g, '');
    }
    if (typeof bValue === 'string') {
      bValue = bValue.replace(/,/g, '');
    }

    // 尝试转换为数字进行比较
    const numA = parseFloat(aValue);
    const numB = parseFloat(bValue);

    if (!isNaN(numA) && !isNaN(numB)) {
      aValue = numA;
      bValue = numB;
    }

    let result = 0;
    if (aValue < bValue) {
      result = -1;
    } else if (aValue > bValue) {
      result = 1;
    }

    return sortState.order === 'asc' ? result : -result;
  });
});

// 文件输入引用
const fileInput = ref(null);

// 导出到Excel
const exportToExcel = () => {
  // 准备导出数据
  const exportData = tableData.value.map(item => {
    const exportItem = {};
    tableColumns.forEach(col => {
      exportItem[col.title] = item[col.dataIndex];
    });
    return exportItem;
  });

  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(exportData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '生产计划数据');

  // 导出文件
  XLSX.writeFile(wb, '生产计划数据.xlsx');
  // message.success('导出成功');
};

// 导入数据
const importFromExcel = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);
      console.log('读取的Excel数据:', jsonData);

      if (jsonData.length === 0) {
        message.warning('Excel文件中没有数据');
        return;
      }

      // 将导入的数据转换为表格所需格式
      const importedData = jsonData.map((item, index) => {
        // 获取Excel中的数据，支持多种可能的列名
        const productLine = item.productLine || item.生产线 || item['生产线'] || item['productLine'] || '';
        const productName = item.productName || item.产品名称 || item['产品名称'] || item['productName'] || '';
        const plannedQuantity = parseInt(item.plannedQuantity || item.计划产量 || item['计划产量'] || item['plannedQuantity'] || 0);
        const actualQuantity = parseInt(item.actualQuantity || item.实际产量 || item['实际产量'] || item['actualQuantity'] || 0);
        const defectQuantity = parseInt(item.defectQuantity || item.不良品数 || item['不良品数'] || item['defectQuantity'] || 0);
        const manager = item.manager || item.负责人 || item['负责人'] || item['manager'] || '';
        const status = item.status || item.状态 || item['状态'] || item['status'] || '';

        // 计算良品率和执行率
        const yieldRate = plannedQuantity ? ((actualQuantity - defectQuantity) / plannedQuantity * 100).toFixed(2) : '0.00';
        const executionRate = plannedQuantity ? (actualQuantity / plannedQuantity * 100).toFixed(2) : '0.00';

        return {
          key: allTableData.value.length + index,
          id: allTableData.value.length + index + 1,
          productLine,
          productName,
          plannedQuantity: plannedQuantity.toLocaleString(),
          actualQuantity: actualQuantity.toLocaleString(),
          defectQuantity: defectQuantity.toLocaleString(),
          yieldRate,
          executionRate,
          manager,
          status
        };
      });

      // 将导入的数据追加到所有数据中
      allTableData.value = [...allTableData.value, ...importedData];
      pagination.total = allTableData.value.length;

      // 更新当前页显示的数据
      updateCurrentPageData();

      console.log('导入的数据:', importedData);
      console.log('所有数据总数:', pagination.total);
      message.success(`成功导入 ${jsonData.length} 条数据，当前共 ${pagination.total} 条数据`);
    } catch (error) {
      console.error('导入失败:', error);
      message.error('导入失败: ' + error.message);
    } finally {
      // 清空文件输入
      event.target.value = '';
    }
  };
  reader.readAsArrayBuffer(file);
};
</script>

<template>
  <div class="manufacturing-chart-page h-screen flex flex-col">
    <!-- 图表区域 -->
    <div class="grid grid-cols-1 gap-10px md:grid-cols-2 flex-shrink-0" style="height: 35vh; margin-top: 10px;">
      <!-- 堆叠面积图 -->
      <div class="chart-card bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper">
          <div class="text-14px font-bold chart-title-text">各产品线产量趋势</div>
        </div>
        <div ref="stackedAreaChartRef" class="flex-grow overflow-hidden"></div>
      </div>

      <!-- 条形图 -->
      <div class="chart-card bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper">
          <div class="text-14px font-bold chart-title-text">各生产线效率对比</div>
        </div>
        <div ref="barChartRef" class="flex-grow overflow-hidden"></div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="flex-grow overflow-hidden mt-8px">
      <div class="bg-white p-10px rounded-4px shadow-sm h-full flex flex-col">
        <div class="chart-title-wrapper" style="display: flex; justify-content: space-between; align-items: center;">
          <div class="text-14px font-bold chart-title-text">生产计划执行情况</div>
          <div style="margin-top: -10px;">
            <AButton type="primary" @click="exportToExcel" class="mr-2">导出Excel</AButton>
            <AButton @click="importFromExcel" class="mr-2">导入Excel</AButton>
          </div>
        </div>
        <div class="flex-grow overflow-hidden flex flex-col min-h-0">
          <!-- 替换 Table 组件为自定义表格 -->
          <div class="custom-table-wrapper flex-grow flex flex-col">
            <div class="table-container">
              <div class="table-header sticky top-0 z-10">
                <div class="table-row table-head">
                  <div
                    class="table-cell sortable"
                    v-for="col in tableColumns"
                    :key="col.key"
                    :style="{ width: col.width + '%' }"
                    @click="handleSort(col.key)"
                  >
                    {{ col.title }}
                    <span class="ml-1">
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'asc' ? '#fff' : '' }"
                      >↑</span>
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'desc' ? '#fff' : '' }"
                      >↓</span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="table-body overflow-auto flex-grow">
                <div
                  class="table-row"
                  v-for="(row, index) in sortedTableData"
                  :key="row.key"
                  :class="getRowClass(index)"
                >
                  <div class="table-cell" v-for="col in tableColumns" :key="col.key" :style="{ width: col.width + '%' }">
                    <div class="cell-content">{{ row[col.dataIndex] }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="table-pagination">
            <div class="flex items-center">
              <input
                ref="fileInput"
                type="file"
                accept=".xlsx,.xls"
                @change="handleFileUpload"
                style="display: none;"
              />
            </div>
            <a-pagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :show-size-changer="pagination.showSizeChanger"
              :page-size-options="pagination.pageSizeOptions"
              :show-quick-jumper="pagination.showQuickJumper"
              :show-total="pagination.showTotal"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.manufacturing-chart-page {
  background-color: #f5f5f5;
  padding: 0 10px;
  overflow: hidden;
}

.chart-card {
  transition: all 0.3s ease;
}

.chart-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 图表标题样式容器 */
.chart-title-wrapper {
  margin: 0 -10px;
  padding: 0 10px 8px;
  position: relative;
}

.chart-title-wrapper::after {
  content: "";
  position: absolute;
  bottom: 8px;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #e8e8e8;
}

/* 表格标题样式 */
.bg-white.p-10px.rounded-4px.shadow-sm.h-full.flex.flex-col > .chart-title-wrapper {
  margin: 0 -10px 10px -10px;
}

/* 图表标题文字样式 */
.chart-title-text {
  padding-bottom: 8px;
}

/* 添加自定义表格样式 */
.custom-table-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-header {
  background-color: #1F77B4 !important;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
  display: flex;
  min-width: 100%;
}

.table-header .table-cell {
  color: white;
  font-weight: bold;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
}

.table-body {
  flex-grow: 1;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  min-width: 100%;
}

.table-row:last-child {
  border-bottom: none;
}

.table-head {
  font-weight: bold;
}

.table-cell {
  padding: 4px 8px;
  border-right: 1px solid #e8e8e8;
  font-size: 13px;
  white-space: nowrap;
  color: #333;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.table-cell:last-child {
  border-right: none;
}

.cell-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.table-row-even {
  background-color: white;
}

.table-row-odd {
  background-color: #EFF4F9;
}

.table-body .table-row:hover {
  background-color: #e6f7ff !important;
}

.table-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.surely-table-wrapper .surely-table-pagination) {
  margin: 8px 0 !important;
}
:deep(.table-card .ant-card-body) {
  padding-bottom: 10px !important;
}

/* 排序相关样式 */
.sortable {
  cursor: pointer;
  user-select: none;
}
</style>
